public class Offer18 {
    public ListNode deleteNode(ListNode head, int val) {
        if (head==null) return null;
        if (head.val==val){
            return head.next;
        }
        ListNode temp = head;
        while (temp!=null){
            if (temp.val==val){
                if (temp.next!=null){
                    temp.val=temp.next.val;
                    temp.next=temp.next.next;
                    break;
                }else {
                    ListNode tail = head;
                    while (tail!=null&&tail.next!=null){
                        if (tail.next.val==val){
                            tail.next = null;
                            break;
                        }
                        tail=tail.next;
                    }
                    break;
                }
            }else {
                temp=temp.next;
            }
        }
        return head;
    }
}
